package com.wlstock.funi.MissionInstance;

import android.content.Context;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.em.mission.Mission;
import com.em.mission.MissionItem;
import com.em.mission.MissionListener;
import com.em.mission.MissionResultListener;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.constant.URLConstant;
import com.wlstock.funi.dao.SelfFundHisDao;
import com.wlstock.funi.model.SelfFundHisModel;
import com.wlstock.funi.request.CustomStringRequest;
import com.wlstock.funi.request.EventBusConstants;
import com.wlstock.funi.request.NetWorkListener;
import com.wlstock.funi.request.ParseNetResponseListener;
import com.wlstock.funi.request.WenGuRequest;
import com.wlstock.funi.utils.StockUtils;
import com.wlstock.funi.utils.TimeUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import static com.wlstock.funi.utils.TimeUtils.dateDiff;

/**
 * Created by admin on 16/9/24.
 */

public class MinPeriodKLineMission extends MissionItem implements MissionListener, NetWorkListener, ParseNetResponseListener {

    public static final int DEFAULT_REQ_LEN = 40;//一周的长度
    private static final int DEFAULT_DAY_DATAS_COUNT = 30;
    private static MinPeriodKLineMission instance;

    private SelfFundHisModel reqModel;
    private CustomStringRequest kLineReq;
    private WenGuRequest     dayReq;

    public MinPeriodKLineMission(Context mContext,SelfFundHisModel reqModel) {
        this.missionName = reqModel.getStkName();
        this.mContext = mContext;
        this.reqModel = reqModel;
    }

    public void start(MissionResultListener resultListener){
        this.resultListener = resultListener;
        start(this, resultListener);
    }

    @Override
    public void beforeExecuteListener(Mission mission) {

    }

    @Override
    public void onExecute(Mission mission) {

        switch (reqModel.getKLINEPeriod()) {
            case MIN5:
            case MIN10:
            case MIN30:
            case MIN60:
                reqHourData(reqModel);
                break;
            case DAY:
                reqDayData(reqModel);
                break;
            case NONE:
                return;
        }
    }

    private void reqDayData(SelfFundHisModel reqModel) {
        if (kLineReq == null){
            kLineReq = new CustomStringRequest();
        }
        kLineReq.parseListener = this;
        kLineReq.networkResponseListener = this;
//        http://d.10jqka.com.cn/v2/line/sh_600448/01/last.js
        String tag = StockUtils.parsetStkCode2ZB(reqModel.getStkCode())+"_"+reqModel.getStkCode();
        String reqUrl = "http://d.10jqka.com.cn/v2/line/"+tag+"/01/last.js";
        kLineReq.request(Request.Method.GET, URLConstant.WENGUPC, null,null, reqUrl, tag);
    }


    private void reqHourData(SelfFundHisModel reqModel) {
        long reqLen = DEFAULT_REQ_LEN;
        SelfFundHisModel model = SelfFundHisDao.getInstance(mContext).queryLastPeriodModel(reqModel.getStkCode(),reqModel.getPeriodStr());
        if (model!=null && model.getRealDate()!=null){
            long diff = TimeUtils.dateDiff(new Date(),model.getRealDate())+1;
            reqLen = StockUtils.caculatePeriodNumsPerDay(reqModel.getKLINEPeriod()) * diff;
        }
        if (reqLen >=DEFAULT_REQ_LEN)
            reqLen = DEFAULT_REQ_LEN;
        int scale = 0;

        switch (reqModel.getKLINEPeriod()){
            case MIN5:
                scale = 5;
                break;
            case MIN10:
                scale = 10;
                break;
            case MIN30:
                scale = 30;
                break;
            case MIN60:
                scale = 60;
                break;
            default:
                return ;
        }
        StringBuffer sb = new StringBuffer("http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?");
        sb.append("symbol=").append(StockUtils.parsetStkCode2ZB(reqModel.getStkCode())+reqModel.getStkCode()).append("&scale=").append(scale).append("&datalen=").append(reqLen);

        if (kLineReq == null){
            kLineReq = new CustomStringRequest();
        }

        kLineReq.networkResponseListener = this;
        kLineReq.request(Request.Method.GET, URLConstant.SINA_HOST,null , null, sb.toString(), reqModel.getStkCode()+"_"+reqModel.getPeriodStr());
    }

    @Override
    public void afterExecute(Mission mission) {

    }


    @Override
    public void onErrorResponse(VolleyError error, EventBusConstants eventCode) {

    }

    @Override
    public void onErrorResponse(VolleyError error, String eventCode) {
        if (resultListener != null){
            resultListener.executeFaile(this);
        }
    }

    @Override
    public void onResponse(String response, EventBusConstants eventCode) {

    }

    @Override
    public void onResponse(String response, String eventCode) {
        switch (reqModel.getKLINEPeriod()) {
            case MIN5:
            case MIN10:
            case MIN30:
            case MIN60:
                parseHourData(response, eventCode);
                break;
            case DAY:
                parseDayData(response,eventCode);
                break;
            case NONE:
                return;
        }
    }

    private void parseDayData(String response, String eventCode) {
        if (response!=null){
            final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            FundAsyTask<String, Void, String> task = new FundAsyTask<String, Void, String>();
            task.backListener = new FundAsyTask.TaskLitener<String, String>() {
                @Override
                public String doInBackground(String... params) {
                    String serverResponse = params[0];
                    String serverEventCode = params[1];
                    String prefix = "quotebridge_v2_line_"+serverEventCode+"_01_last(";
                    if (serverResponse.startsWith(prefix)){
                        try {
                            serverResponse = serverResponse.replace(prefix,"");
                            serverResponse = serverResponse.substring(0,serverResponse.length()-1);
                            JSONObject obj = new JSONObject(serverResponse);
                            String data = obj.getString("data");
                            String[] kLineDatas = data.split(";");
                            if (kLineDatas!=null && kLineDatas.length>0){
                                int count = 0;
                                //只拿最后的20个数据

                                SelfFundHisModel lastModel = SelfFundHisDao.getInstance(mContext).queryLastPeriodModel(reqModel.getStkCode(), reqModel.getPeriodStr());
                                ArrayList<SelfFundHisModel> models = new ArrayList<>();
                                for (int i = kLineDatas.length-1; i>=0 && count<=DEFAULT_DAY_DATAS_COUNT ;i--){
                                    String klineData = kLineDatas[i];
                                    String[] detail = klineData.split(",");
                                    if (detail.length == 8){
                                        Date date = sdf.parse(detail[0]);
//                                        if (date==null || !isDataInRange(lastModel, date, TimeUtils.TIME_PERIOD.DAY, 2)){
//                                            continue;
//                                        }
                                        float  open = Float.valueOf(detail[1]);
                                        float  high = Float.valueOf(detail[2]);
                                        float  low  = Float.valueOf(detail[3]);
                                        float  close= Float.valueOf(detail[4]);

                                        //这里可以计算MA5 以及MA10?
                                        SelfFundHisModel cloneModel = reqModel.clone();
                                        cloneModel.setDatas(open,high,low,close,0,0,0,date);
                                        models.add(cloneModel);
                                        count++;
                                    }
                                }
                                SelfFundHisDao.getInstance(mContext).createOrUpDateDatas(models);
                                String info = reqModel.getStkName() + reqModel.getPeriodStr() + "K线获取成功";
                                return info;
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    return null;
                }
            };

            task.resultListener = new FundAsyTask.TaskResultListener<String>() {
                @Override
                public void onPostResult(String info) {
                    if (info != null) {
                        if (resultListener != null) {
                            resultListener.executeSuccess(info, MinPeriodKLineMission.this);
                        }
                    } else {
                        if (resultListener != null) {
                            resultListener.executeFaile(MinPeriodKLineMission.this);
                        }
                    }
                }
            };
            task.execute(response,eventCode);
        }
    }

    private void parseHourData(String response, String eventCode) {
        //长度应该根据reqModel决定
        FundAsyTask<String, Void, String> task = new FundAsyTask<String, Void, String>();
        task.backListener = new FundAsyTask.TaskLitener<String, String>() {
            @Override
            public String doInBackground(String... params) {
                String[] components = params[1].split("_");

                if (components != null && components.length == 2) {
                    String stkCode = components[0];
                    String periodStr = components[1];

                    try {
                        JSONArray arr = new JSONArray(params[0]);
                        SelfFundHisModel model = SelfFundHisDao.getInstance(mContext).queryLastPeriodModel(stkCode, periodStr);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        ArrayList<SelfFundHisModel> models = new ArrayList<SelfFundHisModel>();
                        for (int i = 0; i < arr.length(); i++) {
                            JSONObject dataObj = arr.getJSONObject(i);

                            String day = dataObj.optString("day");
                            Date date = sdf.parse(day);
                            if (date == null || !isDataInRange(model, date, TimeUtils.TIME_PERIOD.HOUR,30)) {
                                continue;
                            }
                            float open = (float) dataObj.optDouble("open");
                            float high = (float) dataObj.optDouble("high");
                            float low = (float) dataObj.optDouble("low");
                            float close = (float) dataObj.optDouble("close");
                            float ma_price5 = (float) dataObj.optDouble("ma_price5");
                            float ma_price10 = (float) dataObj.optDouble("ma_price10");
                            float ma_price30 = (float) dataObj.optDouble("ma_price30");

                            SelfFundHisModel resultModel = reqModel.clone();
                            resultModel.setDatas(open, high, low, close, ma_price5, ma_price10, ma_price30, date);
                            models.add(resultModel);
                        }

                        SelfFundHisDao.getInstance(mContext).createOrUpDateDatas(models);
                        String info = reqModel.getStkName() + periodStr + "K线获取成功";
                        return info;
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }
                return null;
            }
        };
        task.resultListener = new FundAsyTask.TaskResultListener<String>() {
            @Override
            public void onPostResult(String info) {
                if (info != null) {
                    if (resultListener != null) {
                        resultListener.executeSuccess(info, MinPeriodKLineMission.this);
                    }
                } else {
                    if (resultListener != null) {
                        resultListener.executeFaile(MinPeriodKLineMission.this);
                    }
                }
            }
        };
        task.execute(response, eventCode);
    }

    //只要取30个小时以内的数据即可
    // 比较数据库最新的那条记录,与从服务器拿到当前的那条数据的时间,如果服务器上这条时间已经超过30小时,则不插入进去,
    private boolean isDataInRange(SelfFundHisModel model, Date date, TimeUtils.TIME_PERIOD period , int maxTime) {
        if (model == null || model.getRealDate()== null)
            return true;
        return dateDiff(model.getRealDate(), date, period)<maxTime;
    }

    @Override
    public String parseResponse(NetworkResponse response){
        //问股中需要用到的
        try {
            String s = new String(response.data, "UTF-8");
            return s;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
